import React, { Component } from 'react';
import { connect } from 'react-redux';
import $ from 'jquery';
import {
  Alert,
  Breadcrumb,
  Button,
  Container,
  Card,
  Col,
  ListGroup,
  Modal,
  Row,
} from 'react-bootstrap';

import { URL } from '../../config';
import AddHostInner from '../../components/deploy/addhost';
import {
  function_add_host,
  function_get_hosts,
  function_remove_host
} from '../../actions/deploy';

import "./less/host.css";

class App extends Component {

  state = {
    errorFlg: false,
    errorMsg: "",
    selectedIndex: -1,
    showDelModal: false
  }

  componentDidMount(){
    if(this.props.canDeployConnect){
      let projectArr = Object.keys(this.props.projectList);
      if(projectArr.length > 0){
        function_get_hosts(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => { });
      }
    }
  }

  componentDidUpdate(prevProps){
    if (!prevProps.canDeployConnect && this.props.canDeployConnect){
      let projectArr = Object.keys(this.props.projectList);
      if(projectArr.length > 0){
        function_get_hosts(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => { });
      }
    }
  }

  static getDerivedStateFromProps (props, state) {
    let projectArr = Object.keys(props.projectList);
    if (props.roleList.indexOf(1) === -1) {
      return {
        errorFlg: true,
        errorMsg: "非管理员无权操作"
      };
    } else if (projectArr.length === 0) {
      return {
        errorFlg: true,
        errorMsg: "请先创建项目"
      };
    } else if (props.deployUrl === null) {
      return {
        errorFlg: true,
        errorMsg: "尚未设置客户端工具链接地址，点击<a href=\"" + URL.download_page + "\">这里</a>进行设置"
      };
    } else if (!props.canDeployConnect) {
      return {
        errorFlg: true,
        errorMsg: "无法连接到" + props.deployHost + "，请检查服务器配置"
      };
    } else {
      return {
        errorFlg: false,
        errorMsg: ""
      }
    }
  }

  setShowDelModal () {
    this.setState({ showDelModal: true });
  }

  setHideDelModal () {
    this.setState({ showDelModal: false });
  }

  cleanForm () {
    $("#hostName").val("");
    $("#host").val("");
    $("#username").val("");
    $("#password").val("");
    $("#privateKeyPath").val("");
    $("#hostName").attr("readonly", false);
    $("#projectId").attr("disabled", false);
    this.setState({
      selectedIndex: -1,
      showDelModal: false
    });
  }

  handleSelect (index) {
    this.setState({ selectedIndex: index });
    let item = this.props.hosts[index];
    $("#projectId").val(item.projectId);
    $("#hostName").val(item.hostName);
    $("#host").val(item.host);
    $("#port").val(item.port);
    $("#username").val(item.username);
    $("#password").val("");
    $("#privateKeyPath").val("");
    $("#hostName").attr("readonly", true);
    $("#projectId").attr("disabled", true);
  }

  handleSubmit () {
    if (this.props.canDeployConnect) {
      $("#projectId").attr("disabled", false);
      let selectProject = parseInt($("#projectId").val());
      if (this.state.selectedIndex === -1) {
        for (let item of this.props.hosts) {
          if (item.projectId === selectProject && item.hostName === $("#hostName").val()) {
            this.setState({
              errorFlg: true,
              errorMsg: "主机已存在"
            });
            return;
          }
        }
      } else {
        $("#projectId").attr("disabled", true);
      }
      function_add_host(this.props.deployUrl, selectProject, () => {
        this.cleanForm();
        let projectArr = Object.keys(this.props.projectList);
        function_get_hosts(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => { });
      });
    }
  }

  handleDelHost () {
    let selectProject = parseInt($("#projectId").val());
    function_remove_host(this.props.deployUrl, selectProject, () => {
      this.cleanForm();
      let projectArr = Object.keys(this.props.projectList);
      function_get_hosts(this.props.deployUrl, projectArr.join(","), this.props.dispatch, () => { });
    });
  }

  render () {
    return (
      <Container>
        <Breadcrumb>
          <Breadcrumb.Item href={URL.main_page}>主页</Breadcrumb.Item>
          <Breadcrumb.Item active>服务器连接</Breadcrumb.Item>
        </Breadcrumb>
        <Row>
          <Col sm={8}>
            <Card className="addHostBox">
              <Card.Header>
                {this.state.selectedIndex === -1 ? "添加服务器链接" : "修改服务器链接"}
              </Card.Header>
              <Card.Body>
                {this.state.errorFlg ?
                  <Alert variant="danger">
                    <div dangerouslySetInnerHTML={{ __html: this.state.errorMsg }}></div>
                  </Alert>
                  :
                  <Alert variant="success">
                    { "注意：服务器连接信息保存在 "+this.props.deployHost+" 服务器上的 /usr/local/onlinetool/config 文件中，部署时将从该服务器连接到您配置的服务器" }
                  </Alert>
                }
                <AddHostInner />
              </Card.Body>
              {!this.state.errorFlg ?
                <Card.Footer>
                  {this.state.selectedIndex >= 0 ?
                    <Button className="delBtn" variant="outline-danger" block onClick={this.setShowDelModal.bind(this)}>删除服务器链接</Button>
                    : null}
                  <Button variant="secondary" onClick={this.cleanForm.bind(this)}>
                    取消
                  </Button>
                  <Button variant="primary" onClick={this.handleSubmit.bind(this)}>
                    {this.state.selectedIndex === -1 ? "添加" : "保存"}
                  </Button>
                </Card.Footer>
              : null}
            </Card>
          </Col>
          <Col sm={4}>
            <Card>
              <Card.Header>服务器连接</Card.Header>
              <ListGroup className="listHosts" variant="flush">
                {this.props.hosts.map((item, key) => {
                  return (
                    <ListGroup.Item key={key} onClick={this.handleSelect.bind(this, key)}>
                      <div className="icon">&#xe853;</div>
                      <div className="body">
                        <span className="title">{this.props.projectList[item.projectId].name}/{item.hostName}</span>
                        <span className="extend">{item.username}@{item.host}</span>
                      </div>
                    </ListGroup.Item>
                  )
                })}
              </ListGroup>
            </Card>
          </Col>
        </Row>
        {this.state.showDelModal ?
          <Modal show={this.state.showDelModal} onHide={this.setHideDelModal.bind(this)}>
            <Modal.Header closeButton>
              <Modal.Title>删除服务器链接</Modal.Title>
            </Modal.Header>
            <Modal.Body>你确定要删除{this.props.hosts[this.state.selectedIndex].hostName}？</Modal.Body>
            <Modal.Footer>
              <Button variant="secondary" onClick={this.setHideDelModal.bind(this)}>
                取消
              </Button>
              <Button variant="primary" onClick={this.handleDelHost.bind(this)}>
                删除
              </Button>
            </Modal.Footer>
          </Modal>
          : null}
      </Container>
    )
  }
}

function mapStateToProps (state) {
  return {
    deployUrl: state.deploy.deployUrl,
    deployHost: state.deploy.deployHost,
    projectList: state.project,
    hosts: state.deploy.hosts,
    canDeployConnect: state.deploy.canDeployConnect,
    roleList: state.account.roleList,
  }
}

export default connect(mapStateToProps)(App);